package com.easybuy.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;
import com.easybuy.entity.User;
import com.easybuy.service.UserService;
import com.easybuy.service.impl.UserServiceImpl;
import com.easybuy.util.ReturnResult;

public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		// 目的：一个Servlet可以处理多个请求
		String action = request.getParameter("action");
		if (action != null) {
			switch (action) {
			case "toLogin":
				request.getRequestDispatcher("pre/login.jsp").forward(request, response);
				break;
				
			case "doLogin":
				doLogin(request,response);
				break;
			case "doLogout":
				doLogout(request,response);
				break;

			default:
				break;
			}
		} else {
			response.sendRedirect("404.jsp");
		}
	}

	private void doLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
		//将loginUser 移出session 
		request.getSession().removeAttribute("loginUser");
		
		//，跳转到登录页面
		response.sendRedirect("login?action=toLogin");
		
	}

	private void doLogin(HttpServletRequest request, HttpServletResponse response) throws IOException {
		
		PrintWriter out = response.getWriter();
		
		String loginName = request.getParameter("loginName");
		
		String password = request.getParameter("password");
		
		User user = userService.login(loginName, password);
        
		ReturnResult returnResult = new ReturnResult(0,"登录失败");
		
        if (user != null) {
        	
        	//将用户信息保存到session
        	request.getSession().setAttribute("loginUser", user);
        	
        	returnResult.setStatus(1);
        	returnResult.setMessage("登录成功");
		}
        String jsonStr = JSON.toJSONString(returnResult);
		
		out.print(jsonStr);
		
		out.flush();
		out.close();
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}

}
